package com.yxuan.springboot.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.yxuan.springboot.constant.config.AlipayConfig;
import com.yxuan.springboot.model.Goods;
import com.yxuan.springboot.model.Orders;
import com.yxuan.springboot.model.UserVip;
import com.yxuan.springboot.service.GoodsService;
import com.yxuan.springboot.service.OrdersService;
import com.yxuan.springboot.service.UserVipService;
import com.yxuan.springboot.util.CodeUtil;
import com.yxuan.springboot.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


/**
 * 
 * @author zchao
 *    Orders业务层实现类
 * @date 2023-05-29 14:57:28
 */
@Slf4j
@Service
@Transactional
public class OrdersServiceImpl extends BaseServiceImpl<Orders> implements OrdersService {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private OrdersService ordersService;

    /**
     * 调取支付宝接口app端支付
     */
    AlipayClient alipayClient = new DefaultAlipayClient(
            AlipayConfig.GATEWAYURL, AlipayConfig.APP_ID, AlipayConfig.MERCHANT_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);

    /**
     * @className: OrdersServiceImpl.java
     * @methodName: appPagePay
     * @effect: app端订单支付
     * @author: JingxuanFan
     * @date: 2023/5/30 19:42
     * @param outTradeNo 订单编号
     * @param totalAmount 订单价格(元)
     * @param subject 商品名称
     * @param passbackParams
    **/
    @Override
    public String appPagePay(String outTradeNo, Double totalAmount, String subject, String passbackParams) throws Exception {
        AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();

        /* 同步通知，支付完成后，支付成功页面*/
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        /* 异步通知，支付完成后，需要进行的异步处理*/
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        /*销售产品码（固定）*/
        String productCode = "QUICK_WAP_WAY";

        /* 进行赋值 */
        AlipayTradeWapPayModel wapPayModel = new AlipayTradeWapPayModel();
        wapPayModel.setOutTradeNo(outTradeNo);
        wapPayModel.setSubject(subject);
        wapPayModel.setTotalAmount(totalAmount.toString());
        wapPayModel.setBody("商品名称");
        //超时时间
        wapPayModel.setTimeoutExpress("2m");
        wapPayModel.setProductCode(productCode);
        wapPayModel.setPassbackParams(passbackParams);
        alipayRequest.setBizModel(wapPayModel);

        /* 格式转换*/
        AlipayTradeAppPayResponse payResponse = alipayClient.sdkExecute(alipayRequest);
        String result = payResponse.getBody().replace('\"', '\'').replace('\n', ' ');
        return result;
    }

    /**
     * @className: OrdersServiceImpl.java
     * @methodName: refund
     * @effect: 退款
     * @author: JingxuanFan
     * @date: 2023/5/30 19:45
     * @param outTradeNo   订单编号
     * @param refundReason 退款原因
     * @param refundAmount 退款金额
     * @param outRequestNo 标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
    **/
    @Override
    public String refund(String outTradeNo, String refundReason, Integer refundAmount, String outRequestNo) throws AlipayApiException {
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        /* 调取接口*/
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"refund_amount\":\"" + refundAmount + "\","
                + "\"refund_reason\":\"" + refundReason + "\","
                + "\"out_request_no\":\"" + outRequestNo + "\"}");
        String result = alipayClient.execute(alipayRequest).getBody();
        return result;
    }

    /**
     * @className: OrdersServiceImpl.java
     * @methodName: query
     * @effect: 交易查询
     * @author: JingxuanFan
     * @date: 2023/5/30 19:48
     * @param outTradeNo 订单编号（唯一）
    **/
    @Override
    public String query(String outTradeNo) throws AlipayApiException {
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        /*请求接口*/
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\"," + "\"trade_no\":\"" + "" + "\"}");
        /*转换格式*/
        String result = alipayClient.execute(alipayRequest).getBody();
        return result;
    }

    /**
     * @className: OrdersServiceImpl.java
     * @methodName: close
     * @effect: 交易关闭
     * @author: JingxuanFan
     * @date: 2023/5/30 19:49
     * @param outTradeNo 订单编号（唯一）
    **/
    @Override
    public String close(String outTradeNo) throws AlipayApiException {
        AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\"," + "\"trade_no\":\"" + "" + "\"}");

        String result = alipayClient.execute(alipayRequest).getBody();

        return result;
    }


    /**
     * @className: OrdersServiceImpl.java
     * @methodName: refundQuery
     * @effect: 退款查询
     * @author: JingxuanFan
     * @date: 2023/5/30 19:50
     * @param outTradeNo   订单编号（唯一）
     * @param outRequestNo 标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
    **/
    @Override
    public String refundQuery(String outTradeNo, String outRequestNo) throws AlipayApiException {
        AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest();

        /** 请求接口*/
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"out_request_no\":\"" + outRequestNo + "\"}");

        /** 格式转换*/
        String result = alipayClient.execute(alipayRequest).getBody();

        return result;
    }

    @Override
    public Result buyKamil(String goodsId, String userId) throws Exception {

        try{
            Goods goods = goodsService.findTById(goodsId);


            //根据userId,goodsId以及支付状态验证订单支付状态，若未支付则返回原来的订单号
//            Orders orderInfo = this.getNoPayOrderByGoodsId(targetUserLogin.getId(),goodsId);
//            if(orderInfo!=null){
//                return ResponseMap(CodeUtil.Susser,null,orderInfo.getOrderId());
//            }


            //查询商品数量，商品是否售空
            int store = Integer.parseInt(goods.getStore()) - 1;
            if (store < 0) {
                return new Result(201,"商品售空");
            }

            // 查询用户是否为会员，如是会员，则将会员价格变为 = 当前需购买的商品价格 减去 用户当前所拥有商品的价格（同等商品除外）
            UserVip userVip = new UserVip();
            userVip.setUserId(Integer.valueOf(userId));
            UserVip userVipInfo = userVipService.findObjectByPramas(userVip);
            // 获取用户会员等级
            Integer userRank = Integer.valueOf(userVipInfo.getVipRank());

            BigDecimal lastPrice = null;
            lastPrice = goods.getPrice();
            // 查询该用户拥有的商品价格
            if(userRank == 1){
                //如果该用户是日会员，找出日会员的商品
                Goods goods1 = goodsService.findTById("3");
                //如果用户买的商品不是日会员，那么订单价格改为商品价格-日会员价格
                if(!goods1.getId().equals(goods.getId())){
                    lastPrice = goods.getPrice().subtract(goods1.getPrice());
                }
            }else if(userRank == 2){
                //用户是月会员
                //找到月会员的商品
                Goods goods1 = goodsService.findTById("4");
                //如果这个用户买的是年会员
                if(goods.getId() == 5){
                //价格改为年会员价格-月会员价格
                    lastPrice = goods.getPrice().subtract(goods1.getPrice());
                }
            }
            //商品未售空，用户下单
            Date date = new Date();
            Orders orders = new Orders();
            orders.setUserLoginId(userId);
            orders.setName("购买" + goods.getName() + "订单");
            orders.setGoodsId(goodsId);
            orders.setOrderId(new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis()); //设置订单编号
            orders.setTotal(lastPrice);  // 设置总价格
            orders.setCreateTime(date); // 设置添加时间
            orders.setOrdersState("0"); // 设置订单状态
            goods.setStore(String.valueOf(store));
            //1.在订单表中添加数据 2.修改商品表中的库存数量3.返回订单号
            if(ordersService.save(orders).equals("saveSuccess") && goodsService.upd(goods).equals("updSuccess")){
                HashMap<String, Object> map = new HashMap<>();
                map.put("orderId",orders.getOrderId());
                return new Result(map,200,"创建订单成功");

            }else {
                return new Result(201,"订单创建失败");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return new Result(201,"操作错误");
        }
    }

}
